<template>
  <div class="app-container">
    <SearchForm
      v-show="showSearch"
      v-model="queryParams"
      :options="options.formOps"
      @onQuery="getList"
    >
      <template #operationTime="{ filterForm }">
        <el-form-item label="投用时间">
          <el-date-picker
            v-model="filterForm.time"
            type="daterange"
            range-separator="-"
            style="width: 100%"
            @change="operationTimeChange"
            format="MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </template>
    </SearchForm>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['inspectionPlan:create']"
          >新增</el-button
        >
      </el-col>

      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:user:remove']"
          >删除</el-button
        >
      </el-col> -->

      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:user:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <Table
      ref="table"
      :auto-featch="true"
      :fetch-data="fetchData"
      :options="options.table"
      actionWidth="250"
    >
      <template #routeId="{ row }">
        {{ row.routeName }}
      </template>
      <template #projectId="{ row }">
        {{ row.projectName }}
      </template>
      <template #periodId="{ row }">
        {{ row.periodTimeName }}
      </template>
      <template #default>
        <el-table-column label="审核状态" align="center" prop="checkStatus">
          <template #default="{ row }">
            {{ mapSatus[row.checkStatus] }}
          </template>
        </el-table-column>
      </template>
      <template #actionButton="{ row }">
        <el-button
          type="text"
          icon="Edit"
          @click="handleEdit(row)"
          v-hasPermi="['inspectionPlan:update']"
          >修改</el-button
        >

        <el-button
          type="text"
          icon="Delete"
          style="color: red"
          @click="handleDel(row)"
          v-hasPermi="['inspectionPlan:delete']"
          >删除</el-button
        >
        <el-button
          type="text"
          style="width: 60px"
          v-if="row.checkStatus !== 2 && row.checkStatus !== 3"
          @click="handleExmiam(row)"
          >审核</el-button
        >
        <el-button
          type="text"
          style="width: 60px"
          v-if="row.checkStatus == 2"
          v-hasPermi="['inspectionPlan:updateInspectionPlanWRelease']"
          @click="handlefb(row)"
          >{{ row.fbState == 0 ? "取消发布" : "发布" }}</el-button
        >
      </template>
    </Table>
    <DialogVform
      :formJson="formJson"
      ref="dialogVform"
      @onSubmit="onSubmit"
      :title="dialogType == 'add' ? '新增巡检点位' : '修改巡检点位'"
      :slots="['planDeptName', 'planUserNames', 'personName']"
    >
      <template #planDeptName>
        <el-form-item label="所属部门" prop="planDeptId" label-position="right">
          <TreeSelect
            v-model="form.planDeptId"
            :options="deptTree"
            @change="changeDept"
            style="width: 100%"
          >
          </TreeSelect>
        </el-form-item>
      </template>
      <template #planUserNames>
        <el-form-item
          label="计划执行人员"
          prop="planUserNames"
          label-position="right"
        >
          <el-input
            v-model="form.planUserNames"
            readonly
            @click="onInnerOpen('planUserNames')"
          >
          </el-input>
        </el-form-item>
      </template>
      <template #personName>
        <el-form-item
          label="责任人"
          prop="planUserNames"
          label-position="right"
        >
          <el-input
            v-model="form.personName"
            readonly
            @click="onInnerOpen('personName')"
          >
          </el-input>
        </el-form-item>
      </template>
      <TableSelect
        ref="userTableSelect"
        :queryApi="listUser"
        :options="[]"
        :rowKey="'userId'"
        rowLabel="nickName"
        @onConfirm="onUserConfirm"
        rowLabelText="用户昵称"
        :maxNum="maxNum"
      >
        <template #formSlot="{ handleQuery, filterForm }">
          <el-col :span="8">
            <el-form-item label="部门名称">
              <el-input
                size="small"
                @change="handleQuery"
                v-model="filterForm.deptName"
                clearable
                style="width: 100%"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="用户名称">
              <el-input
                size="small"
                @change="handleQuery"
                v-model="filterForm.userName"
                clearable
                style="width: 100%"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
        </template>
        <template #tableSlot>
          <el-table-column
            label="部门"
            align="center"
            key="deptName"
            prop="dept.deptName"
          />
          <el-table-column
            label="用户名称"
            align="center"
            key="userName"
            prop="userName"
          />
          <el-table-column
            label="用户昵称"
            align="center"
            key="nickName"
            prop="nickName"
          />
        </template>
      </TableSelect>
    </DialogVform>
    <el-dialog append-to-body v-model="shenheDialog" width="40%" title="审核">
      <template #default>
        <el-form label-width="100px" label-position="left">
          <el-form-item label="审核意见">
            <el-input type="textarea" v-model="shyj"></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" @click="onExmiam(2)"> 通 过 </el-button>
          <el-button type="danger" @click="onExmiam(3)"> 拒 绝 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import Table from "@/components/Table/index.vue";
import SearchForm from "@/components/searchForm/index";
import DialogVform from "@/components/dialogVform/index";
import { apis as APIS } from "@/api/znxj/xjjh.js";
import { apis as XJLX } from "@/api/znxj/xjlx.js";
import { apis as XJSD } from "@/api/znxj/xjsjd.js";

import formJson from "./components/options.json";
import { useAsyncData, useFormJsonNew } from "@/views/hooks/useAsyncData.js";
import TableSelect from "@/components/tableSelect/index";
import { deptTreeSelect, listUser } from "@/api/system/user";

const { proxy } = getCurrentInstance();
const ops = useFormJsonNew(formJson, {
  sort: [],
  sortable: [],
});
const options = reactive({
  table: ops,
  formOps: ops.filter((i) =>
    ["planCode", "planName", "planState", "planUserNames"].includes(i.prop)
  ),
});

const showSearch = ref(true);
const dialogVform = ref();
const table = ref();
const changeDept = (val, label) => {
  form.value.planDeptName = label;
  form.value.planDeptId = val;
};
const userTableSelect = ref();
const userProps = ref("");
const maxNum = ref(1);
const onInnerOpen = (prop) => {
  userProps.value = prop;
  if (userProps.value == "planUserNames") {
    maxNum.value = 1000;
    const { planUserIds, planUserNames } = form.value;
    let values = (planUserIds && planUserIds.split(",")) || [];
    let names = (planUserNames && planUserNames.split(",")) || [];

    userTableSelect.value.open(
      values.map((item, index) => ({
        value: values[index],
        label: names[index],
      }))
    );
  } else {
    maxNum.value = 1;

    const { personId, personName } = form.value;
    let values = (personId && personId.split(",")) || [];
    let names = (personName && personName.split(",")) || [];

    userTableSelect.value.open(
      values.map((item, index) => ({
        value: values[index],
        label: names[index],
      }))
    );
  }
};
const onUserConfirm = (data) => {
  const values = data.map((item) => item.value);
  const names = data.map((item) => item.label);
  if (userProps.value == "planUserNames") {
    form.value.planUserIds = values.join(",");
    form.value.planUserNames = names.join(",");
  } else {
    form.value.personId = values.join(",");
    form.value.personName = names.join(",");
  }
};

const plugEdit = (row) => {
  form.value.planDeptName = row.planDeptName;
  form.value.planDeptId = row.planDeptId;
  form.value.planUserIds = row.planUserIds;
  form.value.planUserNames = row.planUserNames;
  form.value.personId = row.personId;
  form.value.personName = row.personName;
};
const plugSubmit = (data) => {
  return {
    ...data,
    routeName: xjlxList.value[data.routeId],
    periodTimeName: xjsdList.value[data.periodId],
  };
};
const {
  onSubmit,
  fetchData,
  handleAdd,
  handleEdit,
  getList,
  handleDel,
  queryParams,
  dialogType,
  form,
} = useAsyncData({
  APIS,
  formJson,
  dialogVform,
  table,
  proxy,
  plugSubmit,
  plugEdit,
});
const xjsdList = ref({});
const xjlxList = ref({});
const pageForm = {};
const deptTree = ref([]);
onMounted(() => {
  deptTreeSelect().then((response) => {
    deptTree.value = response.data;
  });

  XJLX.query(pageForm).then((res) => {
    res.rows.forEach((item) => {
      xjlxList.value[item.id] = item.routeName;
    });
  });
  XJSD.query(pageForm).then((res) => {
    res.rows.forEach((item) => {
      xjsdList.value[item.id] = item.timeName;
    });
  });
});

// 审核相关逻辑
const shyj = ref("");
const shRow = ref({});
const shenheDialog = ref(false);
const close = () => {
  shenheDialog.value = false;
};

const onExmiam = (checkStatus) => {
  if (shyj.value) {
    APIS.sh({
      examineOpinion: shyj.value,
      id: shRow.value.id,
      checkStatus,
    }).then((res) => {
      getList();
      close();
    });
  } else {
    proxy.$message.error("请输入审核意见");
  }
};

const handleExmiam = (row) => {
  shyj.value = "";

  shenheDialog.value = true;
  shRow.value = row;
};
const mapSatus = {
  1: "待审核",
  2: "已通过",
  3: "未通过",
};

// 发布

const handlefb = (row) => {
  proxy.$modal.confirm("是否确认操作 ？").then(function () {
    APIS.fb({
      id: row.id,
      fbState: row.fbState === 0 ? 1 : 0,
    }).then(() => {
      getList();
    });
  });
};
</script>

<style lang="scss" scoped></style>
